package com.gxa.jjty.phy.service.impl;

import com.gxa.jjty.core.common.JsonResult;
import com.gxa.jjty.phy.service.NewsService;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service("newsService")
public class NewsServiceImpl implements NewsService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    public static final String NEWS="newsList";

    public String transfer(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String time = simpleDateFormat.format(new Date());
        return time;
    }


    @Override
    public void insert(Long phyId,String title,String content) {
        ListOperations<String, Object> listOps = redisTemplate.opsForList();
        Map<String,Object> map = new HashMap<>();
        map.put("time",transfer());
        map.put("title",title);
        map.put("content",content);
        redisTemplate.opsForList().leftPush("newsList:"+phyId.toString(),map);
        /*final JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        return jsonResult.getDataMap();*/
    }

    @Override
    public Map<String, Object> selectAll(Long phyId) {
        ListOperations<String, Object> listOps = redisTemplate.opsForList();
        List<Object> range = listOps.range("newsList:"+phyId.toString(), 0, -1);
        final  JsonResult jsonResult = new JsonResult();
        jsonResult.setData(range);
        jsonResult.setCode("1");
        return jsonResult.getDataMap();
    }

    @Override
    public Map<String, Object> empty(Long phyId) {
        ListOperations<String, Object> listOps = redisTemplate.opsForList();
        List<Object> range = listOps.range("newsList:" + phyId.toString(), 0, -1);
        for(int i=0;i<range.size();i++){
            listOps.leftPop("newsList:"+phyId.toString());
        }
        final  JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("消息已清空");
        return jsonResult.getDataMap();
    }
}
